package org.onepiece.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.onepiece.admin.entity.dto.context.OrderContext;
import org.onepiece.admin.entity.onepiece.SysUser;
import org.onepiece.admin.entity.vo.SysUserVO;
import org.onepiece.admin.integration.manager.OrderService;
import org.onepiece.admin.integration.service.SysUserService;
import org.onepiece.admin.mapper.onepiece.SysUserMapper;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author hautxxxyzjk@163.com
 * @since 2022-08-24 22:22:16
 */
@AllArgsConstructor
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper sysUserMapper;
    private final AsyncTaskExecutor asyncTaskExecutorCommon;
    private final List<OrderService> orderServiceList;

    @Override
    public List<SysUser> listXml() {
        // start test
        OrderContext context = new OrderContext();
        orderServiceList.stream()
                .filter(item -> item.supports(context))
                .forEach(item -> item.doHandle(context));
        // end test

        return sysUserMapper.listXml();
    }

    @Override
    public List<SysUserVO> completableFuture() {
        List<CompletableFuture<SysUserVO>> futureList = Lists.newArrayList();
        List<SysUserVO> list = new ArrayList<>();

        Stream.of(1, 2, 3, 4, 5, 6, 7).forEach(id -> {
            CompletableFuture<SysUserVO> completableFuture = CompletableFuture.supplyAsync(() -> {
                        SysUser sysUser = sysUserMapper.selectById(id);
                        SysUserVO sysUserVO = new SysUserVO();
                        sysUserVO.setId(sysUser.getId());
                        sysUserVO.setUsername(sysUser.getUsername());
                        sysUserVO.setAge(sysUser.getAge());
                        return sysUserVO;
                    }, asyncTaskExecutorCommon)
                    .whenCompleteAsync((sysUserVO, throwable) -> list.add(sysUserVO), asyncTaskExecutorCommon)
                    .exceptionally(throwable -> {
                        log.error("SysUserServiceImpl#completableFuture task get exception", throwable);
                        return null;
                    });
            futureList.add(completableFuture);
        });
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
        return list.stream().filter(Objects::nonNull).collect(Collectors.toList());
    }
}
